import moment from 'moment'
import initPeaks from './initPeaks'


const decodeArrayBuffer = (arraybuffer, callback) => {
  if (!window.WaveSurferOfflineAudioContext) {
    window.WaveSurferOfflineAudioContext = new (window.OfflineAudioContext ||
      window.webkitOfflineAudioContext)(1, 2, 44100);
  }
  window.WaveSurferOfflineAudioContext.decodeAudioData(arraybuffer, buffer => callback(buffer))
}


const loadArrayBuffer = (data) => {

  let dv = new DataView(data)
  // console.log(dv);
  let collectionTime = moment(Number(dv.getBigInt64(0, true))).format('YYYY-MM-DD HH:mm:ss')
  let arrivalTime = moment(Number(dv.getBigInt64(8, true))).format('YYYY-MM-DD HH:mm:ss')
  let currentTime = Date.now()

  return (callback) => {
    decodeArrayBuffer(data.slice(16), buffer => {
      // console.log(buffer);
      let width = Math.floor(buffer.duration * 3)
      let peakHeight = initPeaks(buffer, width)
      let message = {
        collectionTime,
        arrivalTime,
        currentTime,
        buffer,
        canvasInfo: {
          peakHeight,
          color: null,
          collectionTime: collectionTime
        }
      }
      callback(message)
    })
  }


}

export default loadArrayBuffer

